package com.gillion.grule.client.components;

import com.gillion.grule.client.core.Component;
import com.gillion.grule.client.core.Context;
import com.gillion.grule.client.core.ExecuteComponent;
import com.gillion.grule.client.exception.ExecutorException;
import com.gillion.grule.client.service.InParameterMustService;
import com.gillion.grule.client.utils.ContextHolder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




@Component("InParameter")
public class InParameterComponent
        extends ExecuteComponent
{
    static Logger logger = LoggerFactory.getLogger(InParameterComponent.class);








    public <T> T execute(String express, Context context) {
        Object result = null;
        String[] expres = express.split("\\|");
        if (expres.length == 1 || (expres.length == 3 && expres[1].equals("false"))) {
            result = param(expres[0], context);



            return (T)result;
        }  if (expres.length == 3 && expres[1].equals("true")) {
            result = param(expres[0], context);
            if (result == null || "".equals(result.toString())) {
                InParameterMustService inParameterMustService = (InParameterMustService)ContextHolder.getBean("inParameterMustService");
                inParameterMustService.exccute(express, context);
                throw new ExecutorException(50001, expres[2] + "为空!对象内容：" + context.getParams().toString());
            }
            return (T)result;
        }
        return (T)result;
    }

    private Object param(String express, Context context) {
        List<String> exp = Arrays.asList(express.split("\\."));
        Object obj = null;
        for (int i = 0; i < exp.size(); i++) {
            if (((String)exp.get(i)).startsWith("params[") && ((String)exp.get(i)).endsWith("]")) {
                Integer index = Integer.valueOf(0);
                Pattern pattern = Pattern.compile("(?<=\\[)(\\S+)(?=\\])");
                Matcher matcher = pattern.matcher(exp.get(i));
                while (matcher.find()) {
                    index = Integer.valueOf(Integer.parseInt(matcher.group()));
                }
                obj = context.getParams().get(index.intValue());
            }
            else if (obj != null) {
                try {
                    obj = ((Map)obj).get(exp.get(i));
                } catch (Exception e) {
                    obj = "";
                }
            }
        }


        return obj;
    }
}